package mymusic;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import sun.audio.AudioPlayer;
import sun.audio.AudioStream; 

public class MyMusic extends Thread{
	
	private FileInputStream fis=null;
	private AudioStream as=null;
	private ByteArrayOutputStream bos=null;
	private String file;
	public final static int MUSIC=1;
	public final static int AUDIO=0;
	private int type=0;
	private boolean stop=false;
//	private int loop=0;
	
//	讲文件字节流读到内存中的字节数组流中，用来重复读取
	public MyMusic(String file,int i)
	{
		this.file=file;
		type=i;
		if(this.file==null)
			return;
		try
		{
			fis=new FileInputStream(this.file);
			bos=new ByteArrayOutputStream();
			
			byte[]buf=new byte[1024];
			int len=0;
			
			try
			{	
				
				while((len=fis.read(buf))!=-1)
				{
					bos.write(buf, 0, len);
				}
				
				bos.flush();
			}
			catch(IOException ioe)
			{
				ioe.printStackTrace();
			}
			
		}
		catch(FileNotFoundException e )
		{
			e.printStackTrace();
		}
		finally
		{
			try
			{
				if(fis!=null)
					fis.close();
			}
			catch(IOException e)
			{
				e.printStackTrace();
			}
		}
		
		
	}
	public void run()
	{
		if(type==AUDIO)
		play();
		else
		{
			while(!stop)
			{
				play();
			}
		}
	}
	public InputStream getInpuStream()
	{
		if(bos==null)
		{
			return null;
		}
		return new ByteArrayInputStream(bos.toByteArray());
	}
	 // 一次播放 停止   
    public void stop(boolean b)   
    {   
    	 stop=b; 		
    }   
	public void play()
	{
	
		 if( bos==null ){   
	            System.out.println("AudioStream object is not created!");   
	            return;   
		 }
		 else
		 {
			try
			{
				{
									
//				获取声音字节流的副本变成音频流
				as=new AudioStream(this.getInpuStream());
//				播放声音
				AudioPlayer.player.start(as);
				
				}
				
			}
			catch(IOException ioe)
			{
				ioe.printStackTrace();
			}
			finally
			{
				try {
					
								//等待声音播放完成
						try {
//							如果是音效时
								if(type==AUDIO)
									Thread.sleep(1000);
								else
								{
									Thread.sleep(106000);
								}
							} 
						catch (InterruptedException e) 
							{
								// TODO 自动生成的 catch 块
								e.printStackTrace();
							}
//					关闭声音
					if(as!=null)
						as.close();

				} 
				catch (IOException e)
				{
					// TODO 自动生成的 catch 块
					e.printStackTrace();
				}
			}
		
		 }
					
	}
}
